package org.turnlink.sclm.dao.hibernate;

import java.sql.Date;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.turnlink.sclm.dao.AccountSessionDao;
import org.turnlink.sclm.model.AccountSession;


//This will make easier to autowired
@Repository("accountSessionDao")
// Default is read only
@Transactional
public class AccountSessionDaoHibernate implements AccountSessionDao {

	private final Log log = LogFactory.getLog(getClass());

	private HibernateTemplate hibernateTemplate;

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	/*
	 * (non-Javadoc)
	 * @see org.turnlink.sclm.dao.AccountSessionDao#findByToken(java.lang.String)
	 */
	public AccountSession findByToken(String token) {
		List<AccountSession> results = hibernateTemplate.find("from AccountSession where token = ? " , token);
		return results == null || results.isEmpty()
				? null
				: results.get(0);
	}

	/*
	 * (non-Javadoc)
	 * @see org.turnlink.sclm.dao.AccountSessionDao#saveOrUpdate(java.lang.Integer, org.turnlink.sclm.model.AccountSession)
	 */
	public void saveOrUpdate(Integer accountId, AccountSession accountSession) {
		accountSession.setAccountId(accountId);
		hibernateTemplate.saveOrUpdate(accountSession);
	}

	/*
	 * (non-Javadoc)
	 * @see org.turnlink.sclm.dao.AccountSessionDao#deleteOldSessions()
	 */
	public void removeOldSessions() {
		
		Calendar twohoursOld = Calendar.getInstance();
		twohoursOld.add(Calendar.HOUR, -2);
		hibernateTemplate.bulkUpdate("delete from AccountSession where tokenCreation < ? ", new Timestamp(twohoursOld.getTimeInMillis()));
		
	}	

}
